package com.duojuhe.common.component.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;


/**
 * 线程里手动事物处理
 *
 *
 * @date 2018/6/13 0013
 */
@Slf4j
@Component
public class ThreadTransactionManager {
    @Resource(name = "transactionManager")
    private DataSourceTransactionManager transactionManager;

    /**
     * 获取事物状态
     *
     * @return
     */
    public TransactionStatus getTransactionStatus() {
        // spring无法处理thread的事务，声明式事务无效
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 事物隔离级别，开启新事务，这样会比较安全些。
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        // 获得事务状态
        return transactionManager.getTransaction(def);
    }


    /**
     * 提交事务
     *
     * @param status
     */
    public void commit(TransactionStatus status) {
        //提交事物
        transactionManager.commit(status);
    }

    /**
     * 回滚事务
     *
     * @param status
     */
    public void rollback(TransactionStatus status) {
        transactionManager.rollback(status);
    }
}
